/************************************************************
 *  * Hyphenate CONFIDENTIAL
 * __________________
 * Copyright (C) 2016 Hyphenate Inc. All rights reserved.
 *
 * NOTICE: All information contained herein is, and remains
 * the property of Hyphenate Inc.
 * Dissemination of this information or reproduction of this material
 * is strictly forbidden unless prior written permission is obtained
 * from Hyphenate Inc.
 */

#import "UIViewController+SearchController.h"
#import <objc/runtime.h>


static const void *ResultControllerKey = "ResultControllerKey";
static const void *SearchControllerKey = "SearchControllerKey";
BOOL _hidesNavigationBarDuringPresentation;

@implementation UIViewController (SearchController)

#pragma mark - getter & setter

- (BOOL)hidesNavigationBarDuringPresentation{
    return _hidesNavigationBarDuringPresentation;
}

- (void)setHidesNavigationBarDuringPresentation:(BOOL)hidesNavigationBarDuringPresentation{
    _hidesNavigationBarDuringPresentation = hidesNavigationBarDuringPresentation;
}

- (EMSearchResultController *)resultController
{
    return objc_getAssociatedObject(self, ResultControllerKey);
}

- (void)setResultController:(EMSearchResultController *)resultController
{
    objc_setAssociatedObject(self, ResultControllerKey, resultController, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

- (UISearchController *)searchController{
    return objc_getAssociatedObject(self, SearchControllerKey);
}

- (void)setSearchController:(UISearchController *)searchController{
    objc_setAssociatedObject(self, SearchControllerKey, searchController, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

#pragma mark - enable

- (void)enableSearchController{
    self.definesPresentationContext = YES;
    self.extendedLayoutIncludesOpaqueBars  = YES;
    
    self.resultController = [[EMSearchResultController alloc] init];
    self.searchController = [[UISearchController alloc]initWithSearchResultsController:self.hidesNavigationBarDuringPresentation == YES ? self.resultController : nil];
    self.searchController.dimsBackgroundDuringPresentation = YES;
    self.searchController.delegate = self;
    self.searchController.searchResultsUpdater = self;
    self.searchController.searchBar.delegate = self;
    //这个设置搜索框的光标、取消按钮的颜色
    self.searchController.searchBar.tintColor = [UIColor colorWithHexString:@"#767676"];
    //这个是设置搜索框textfield之外的颜色
    self.searchController.searchBar.barTintColor = kBDTextBlackColorGray;
    //隐藏背景图显示，透出来self.view的背景色，方便修改颜色显示
    self.searchController.searchBar.searchBarStyle = UISearchBarStyleProminent;
    UIImageView *barImageView = [[[self.searchController.searchBar.subviews firstObject] subviews] firstObject];
    barImageView.layer.borderColor = [UIColor colorWithHexString:@"#e5e5e5"].CGColor;
    barImageView.layer.borderWidth = 1;
    self.searchController.hidesNavigationBarDuringPresentation = self.hidesNavigationBarDuringPresentation;
    if (self.hidesNavigationBarDuringPresentation == NO) {
        self.resultController.view.backgroundColor = [UIColor clearColor];
        self.resultController.tableView.frame = CGRectMake(0, 108, kBDScreenWidth, kBDScreenHeight - 108);
    }
    //这行代码在ipad下是会崩溃的，在iPhone下是需要的，否则在取消搜索的时候不会重新加载本来的数据
    
    if ([UIDevice currentDevice].systemVersion.floatValue > 9.1) {
        self.searchController.obscuresBackgroundDuringPresentation = NO;  // 9.1  之后的方法
    }
    self.searchController.dimsBackgroundDuringPresentation = NO;
    [self.searchController.searchBar sizeToFit];
    self.searchController.searchBar.placeholder = ASLocalizedString(@"搜索");
}

//将要输入
- (void)willPresentSearchController:(UISearchController *)searchController{
    
    if (self.hidesNavigationBarDuringPresentation == YES) {
        [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleDefault];
        
        UIBlurEffect *effect = [UIBlurEffect effectWithStyle:UIBlurEffectStyleLight];
        UIVisualEffectView *effectView = [[UIVisualEffectView alloc] initWithEffect:effect];
        effectView.frame = self.view.bounds;
        [self.view addSubview:effectView];
        effectView.tag = 9999;
        effectView.alpha = 0;
        
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] init];
        [effectView addGestureRecognizer:tap];
        [[tap rac_gestureSignal] subscribeNext:^(__kindof UIGestureRecognizer * _Nullable x) {
            [self.searchController setActive:NO];
        }];
        
        [UIView animateWithDuration:0.25 animations:^{
            effectView.alpha = 1;
        } completion:^(BOOL finished) {
            
        }];
    }
    
    if ([self respondsToSelector:@selector(willSearchBegin)]) {
        [self willSearchBegin];
    }
}

//将要退出搜索框
- (void)willDismissSearchController:(UISearchController *)searchController{
    
    if (self.hidesNavigationBarDuringPresentation == YES) {
        [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];
        UIVisualEffectView *effectView = [self.view viewWithTag:9999];
        [UIView animateWithDuration:0.25 animations:^{
            effectView.alpha = 0;
        } completion:^(BOOL finished) {
            [effectView removeFromSuperview];
            
        }];
    }
    
    if ([self respondsToSelector:@selector(didSearchFinish)]) {
        [self didSearchFinish];
    }
}


- (void)updateSearchResultsForSearchController:(UISearchController *)searchController{
    if ([self respondsToSelector:@selector(searchTextChangeWithString:)]) {
        [self searchTextChangeWithString:searchController.searchBar.text];
    }
}

- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar{
    if ([self respondsToSelector:@selector(cancelButtonClicked)]) {
        [self cancelButtonClicked];
    }
}

@end

